package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.UserInfo;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class GiteeLoginController {


    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 用来接收临时授权码  gitee发送过来的，
     * @return
     */
    @RequestMapping("/callbackCode.do")
    public String callbackCode(String code, HttpServletResponse response, Model model){

        System.out.println("接收到的临时授权码" + code);
        // 根据code获取token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);
        // 根据token 获取gitee用户信息
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户信息" + JSON.toJSONString(userInfoByToken));

        // 执行注册  （过滤出4个字段  ）
        String name = userInfoByToken.getString(GiteeUtils.UserInfoPropertyEnum.LOGIN.getKey()); // 个人空间地址 当做系统的用户名

        String nickName = userInfoByToken.getString("name");// 用户名当做 系统的昵称

        String avatarUrl = userInfoByToken.getString("avatar_url");//头像

        Integer giteeId = userInfoByToken.getInteger("id"); // 主键 当做 系统的 giteeId

        UserInfo userFromDB = userMapper.selectByName(name);

        if (userFromDB == null){ //之前没有注册过
            UserInfo userInfo = new UserInfo();
            userInfo.setNickName(nickName);
            userInfo.setAvatarUrl(avatarUrl);
            userInfo.setName(name);
            userInfo.setGiteeId(giteeId);

            String pwd = "123";
            String salt = UUID.randomUUID().toString().substring(0, 8);
            String md5String = Md5Utils.getMD5String(pwd + salt);
            userInfo.setSalt(salt);
            userInfo.setPassword(md5String);

            userMapper.add(userInfo);
            // 加密新注册的用户
            TokenUtils.responseTokenByCookie(userInfo,response);
            redisTemplate.opsForValue().set("name",JSON.toJSONString(userInfo),30, TimeUnit.MINUTES);

        }else {
            userFromDB.setAvatarUrl(avatarUrl);
            userFromDB.setNickName(nickName);
            userMapper.updateUser(userFromDB);
            // 加密数据库里的用户
            TokenUtils.responseTokenByCookie(userFromDB,response);
            redisTemplate.opsForValue().set("name",JSON.toJSONString(userFromDB),30,TimeUnit.MINUTES);
        }

        ZzyUtils.sendSms("17611221735","登录成功" + System.currentTimeMillis(),5);

        model.addAttribute("nickName",nickName);
        model.addAttribute("avatarUrl",avatarUrl);
        return  "success";
    }

}
